import env from "@/config";
import store from "@/store"
import {router} from "@/router";

export const http = (options) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: '加载中...',
            mask: options.load || false // 默认遮罩出现可继续操作
        });
        try {
            uni.request({
                url: env.baseUrl + options.url,
                method: options.method ||  'POST', // 默认为POST请求
                data: options.data, //请求超时在manifest.json配置
                sslVerify: false,
                header: options.method == ('POST' || 'UPDATE') ? {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Content-Type': 'application/json; charset=UTF-8',
                    "web_sessionId": store.state.user.vuex_token,
                    "web_deviceNumber": store.state.user.vuex_device_number
                } : {
                    'X-Requested-With': 'XMLHttpRequest',
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                    "web_sessionId": store.state.user.vuex_token,
                    "web_deviceNumber": store.state.user.vuex_device_number
                },
                success: res => {
                    if (res.data.code == 401) {
                        uni.showToast({
                            title: '请先登录',
                            icon: 'none'
                        });
                        router.replace({name: 'login'})
                        return;
                    }
                    if (res.data.code != 200) {
                        reject(res.data);
                    } else {
                        resolve(res.data);
                    }
                },
                fail: (err) => {
                    console.log("请求错误:" + err.errMsg);
                    uni.showToast({
                        title: '请检查网络连接',
                        icon: 'none'
                    });
                    reject(err);
                },
                complete: () => {
                    uni.hideLoading();
                }
            });
        } catch (e) {
            uni.hideLoading();
            uni.showToast({
                title: '服务端异常',
                icon: 'none'
            })
        }

    })
};

export const httpGet = (url, data) => {
    return http({
        url: url,
        method: "GET",
        data: data
    })
};

export const httpPost = (url, data) => {
    return http({
        url: url,
        method: "POST",
        data: data
    })
};

export const httpDelete = (url, data) => {
    return http({
        url: url,
        method: "DELETE",
        data: data
    })
};
